﻿using System;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Home.Mobilesales.Common;
using Home.MobileSales.Common.Entities;

namespace Common.Models
{
    public class SkladRepository
    {
        public List<Sklad> GetSklads()
        {
            List<Sklad> sklads = new List<Sklad>();
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery = "SELECT IdSklad, NameSklad FROM Sklads";

                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            Sklad sklad = new Sklad();
                            int idSklad = dr.GetOrdinal("IdSklad");
                            int nameSklad = dr.GetOrdinal("NameSklad");
                            sklad.IdSklad = dr.GetInt32(idSklad);
                            sklad.NameSklad = dr.IsDBNull(nameSklad) ? string.Empty : dr.GetString(nameSklad);
                            sklads.Add(sklad);
                        }
                        return sklads;
                    }
                }
            }
        }

        public Sklad GetSkladById (int id)
        {
            using (SqlCeConnection connection = WorkDataBase.CreateConnection())
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();

                string sqlQuery =
                    "SELECT IdSklad, NameSklad" +
                    "FROM Sklads " +
                    "Where IdSklad = @IdSklad";

                using (SqlCeCommand command = new SqlCeCommand(sqlQuery, connection))
                {
                    command.Parameters.Add("@IdSklad", id);
                    using (SqlCeDataReader dr = command.ExecuteReader())
                    {
                        Sklad sklad = new Sklad();
                        if (dr.Read())
                        {
                            int idSklad = dr.GetOrdinal("IdGood");
                            int nameSklad = dr.GetOrdinal("NameSklad");
                            sklad.IdSklad = dr.GetInt32(idSklad);
                            sklad.NameSklad = dr.IsDBNull(nameSklad) ? string.Empty : dr.GetString(nameSklad);
                        }
                        return sklad;
                    }
                }
            }
        }
    }
}
